<template>
  <div class="add-health-manage p-10">
    <el-form
      :model="personInfo"
      :rules="rules"
      ref="personInfoRef"
      id="form-header"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="姓名" required prop="name">
            <!-- <el-input
              v-model="personInfo.name"
              placeholder="请输入姓名"
            ></el-input> -->
            <el-autocomplete
              v-model.trim="personInfo.name"
              @select="handleSelect"
              :fetch-suggestions="queryNameAsync"
              placeholder="请输入姓名"
              max-length="18"
              style="width: 82%"
            >
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="证件类型" prop="cardType" label-width="7em">
            <el-select
              v-model="personInfo.cardType"
              placeholder="请选择证件类型"
              ref="cardTypeInput"
            >
              <el-option label="居民身份证" value="居民身份证"></el-option>
              <el-option
                label="港澳台居民身份证"
                value="港澳台居民身份证"
              ></el-option>
              <el-option
                label="外国人永久居留身份证"
                value="外国人永久居留身份证"
              ></el-option>
              <el-option
                label="港澳台居民居住证"
                value="港澳台居民居住证"
              ></el-option>
              <el-option label="居民户口本" value="居民户口本"></el-option>
              <el-option label="护照" value="护照"></el-option>
              <el-option label="军官证" value="军官证"></el-option>
              <el-option label="文职干部证" value="文职干部证"></el-option>
              <el-option label="士兵证" value="士兵证"></el-option>
              <el-option label="驾驶执照" value="驾驶执照"></el-option>
              <el-option label="出生证" value="出生证"></el-option>
              <el-option label="其他" value="其他"></el-option>
              <el-option label="儿保卡" value="儿保卡"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="证件号码"
            required
            label-width="7em"
            prop="cardNumber"
          >
            <!-- <el-input
              v-model="personInfo.cardNumber"
              placeholder="请输入证件号码"
            ></el-input> -->
            <el-autocomplete
              ref="cardNumberInput"
              v-model.trim="personInfo.cardNumber"
              @select="handleSelect"
              :fetch-suggestions="queryCarNumberAsync"
              placeholder="请输入证件号码"
              :maxlength="18"
              style="width: 300px"
                 @blur="getbirthday"
            >
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="出生日期"
            required
            label-width="7em"
            prop="birthday"
          >
            <el-date-picker
              :disabled-date="disableFutureDates"
              v-model="personInfo.birthday"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择出生日期"
              style="width: 300px"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        class="mb-20"
        :data="questionTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          v-for="(col, index) in dataCols"
          :align="index === 0 ? 'left' : 'center'"
          :prop="col.prop"
          :label="col.label"
          :key="col.prop + index"
        >
          <template #header="{ column }">
            <div v-html="column.label"></div>
          </template>
          <template #default="{ row, $index, column }">
            <template v-if="column.property === 'question'">
              <div>( {{ $index + 1 }} ) {{ row.question }}</div>
            </template>
            <template v-else>
              <div :key="index + Math.random()">
                <el-radio
                  @click.native="radioChange"
                  v-model="row.score"
                  :value="column.no"
                  ><span class="px-10">{{ column.no }}</span></el-radio
                >
              </div>
              <div v-if="row.extraTip">
                {{ row.extraTip[column.no - 1] }}
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="bodyTypeTableDataRender"
        :header-cell-class-name="headerCellClassFunc"
        border
        style="width: 100%"
      >
        <el-table-column
          v-for="(col, index) in bodyTypeCols"
          header-align="center"
          align="left"
          :prop="col.prop"
          :label="col.label"
          :key="index + col.prop"
        >
          <template #default="{ column, $index }">
            <div v-if="index === 0">
              {{ leftLabels[$index] }}
            </div>
            <div v-else-if="$index === 0">
              得分:
              {{
                bodyTypeDataObj[`${column.property}${bodyTypebValKeys[$index]}`]
              }}
              <div v-if="$index === 0">
                <el-radio-group
                  disabled
                  v-model="bodyTypeDataObj[`${column.property}Choice`]"
                >
                  <el-radio value="1">是</el-radio>
                  <el-radio value="2">{{
                    index !== 9 ? "倾向是" : "基本是"
                  }}</el-radio>
                  <el-radio value="3">否</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div v-else>
              <el-checkbox-group
                v-model="bodyTypeDataObj[`${column.property}Guidance`]"
              >
                <el-checkbox
                  v-for="(item, gIndex) in healthGuidance"
                  :key="item"
                  :label="gIndex + 1"
                  :value="gIndex + 1"
                >
                  {{ item }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="d-flex jc-center py-10 mt-30">
        <el-button plain @click="resetPage">清空</el-button>
        <el-button type="primary" @click="saveData">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  getDataCols,
  getQuestionTableData,
  getBodyTypeTableData,
  getBodyTypeCols,
  healthGuidance,
} from "@/pages/examples/addHealth/constants.js";
import { debounce } from "lodash";
import { ElMessage } from "element-plus";
import http from "@/utils/request";
let lastIdResults = null;
const disableFutureDates = (time) => time > new Date();
export default {
  data() {
    const validatorIdCard = (rule, value, callback) => {
      setTimeout(() => {
        //@ts-ignore
        const value2 = this.personInfo.cardNumber;
        if (value2 == "") {
          callback(new Error("请输入证件号码"));
          //@ts-ignore
        } else if (
          //@ts-ignore
          !/^\d{15}|^\d{17}[a-z]$/i.test(value2)
          //@ts-ignore
        ) {
          callback(new Error("请输入正确的证件号码"));
        } else {
          callback();
        }
      }, 200);
    };
    return {
      dataCols: getDataCols(),
      questionTableData: getQuestionTableData(),
      bodyTypeDataObj: getBodyTypeTableData().bodyTypeDataObj,
      bodyTypeTableDataRender: getBodyTypeTableData().bodyTypeTableDataRender,
      bodyTypeCols: getBodyTypeCols(),
      healthGuidance,
      redHeaderPropArr: [],
      valueArr: [],
      leftLabels: ["体质辨识", "中医药保健指导"],
      bodyTypebValKeys: ["Score", "Guidance"],
      personInfo: {
        name: "",
        cardNumber: "",
        birthday: "",
        cardType: "居民身份证",
      },
      bmi: "",
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        cardNumber: [
          { required: true, validator: validatorIdCard, trigger: "blur" },
        ],
        birthday: [
          { required: true, message: "请选择出生日期", trigger: "blur" },
        ],
        cardType: [
          { required: true, message: "请选择证件类型", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    isDisableSave() {
      return !this.questionTableData.every((v) => v.score);
    },
    // bodyTypeDataObj 第一个key 生成的三个数据 仅用于展示文字，与需要提交的数据字段无关联因此不需要考虑
    bodyTypeDataKeys() {
      return Object.keys(this.bodyTypeDataObj).slice(3);
    },
  },
  methods: {
    disableFutureDates,
    getbirthday() {
      // if (
      //   this.personInfo.cardNumber &&
      //   this.personInfo.cardNumber.length === 18
      //   &&
      //   this.personInfo.birthday == ""
      //   &&
      //   this.personInfo.cardType == "居民身份证"
      // ) {
      //   const birthday = this.personInfo.cardNumber.substring(6, 14);
      //   this.personInfo.birthday =
      //     birthday.substring(0, 4) +
      //     "-" +
      //     birthday.substring(4, 6) +
      //     "-" +
      //     birthday.substring(6, 8);
      // }
      if (
       this.personInfo.cardNumber &&
       this.personInfo.cardNumber.length === 18 &&
         this.personInfo.cardType == "居民身份证"
      ) {
        const birthday =this.personInfo.cardNumber.substring(6, 14);

        // this.personInfo.birthday =
        //   birthday.substring(0, 4) +
        //   "-" +
        //   birthday.substring(4, 6) +
        //   "-" +
        //   birthday.substring(6, 8);
        const cardNumber =this.personInfo.cardNumber;

        // 1. 获取出生日期部分 (第7到14位)
        const birthdayPart = cardNumber.substring(6, 14);
        // 正则校验是否为有效日期格式
        const dateRegex = /^(\d{4})(\d{2})(\d{2})$/;
        if (dateRegex.test(birthdayPart)) {
          const [, year, month, day] = birthdayPart.match(dateRegex);

          // 校验日期有效性
          const birthDate = new Date(`${year}-${month}-${day}`);
          if (
            birthDate.getFullYear() === parseInt(year) &&
            birthDate.getMonth() + 1 === parseInt(month) &&
            birthDate.getDate() === parseInt(day)
          ) {
            // 设置出生日期
            this.personInfo.birthday = `${year}-${month}-${day}`;
          } else {
            this.personInfo.birthday = ""; // 重置
          }
        } else {
          this.personInfo.birthday = ""; // 重置
        }
      }
      
    },
    // 回填数据
    fillData(obj) {
      this.questionTableData.forEach((row) => {
        const { questionId } = row;
        const newScore = obj[questionId] || 0;
        newScore && (row.score = newScore);
      });
      this.radioChange();
    },
    radioChange() {
      const totalScoreMap = {};
      const { bodyTypeCols, bodyTypeDataObj, questionTableData } = this;
      const dataCols = bodyTypeCols.slice(1);
      dataCols.forEach((item) => {
        const { relateQuestions, prop, label } = item;
        const totalScore = questionTableData
          .filter((_v, index) => relateQuestions.includes(index + 1))
          .reduce((pre, cur) => {
            let { score } = cur;
            const isReverseScore = label === "平和质";
            if (isReverseScore) {
              score = score <= 0 ? 0 : 6 - score;
            }
            return pre + score;
          }, 0);
        totalScoreMap[prop] = totalScore;
        bodyTypeDataObj[`${prop}Score`] = totalScore;
      });
      const propArr = Object.keys(totalScoreMap);
      const valueArr = Object.values(totalScoreMap);
      let redHeaderPropArr = propArr.filter(
        (_v, index) => valueArr[index] >= 11
      );
      bodyTypeDataObj.peacefulQualityChoice !== "1" &&
        (redHeaderPropArr = redHeaderPropArr.filter(
          (v) => v !== "peacefulQuality"
        ));
      this.valueArr = valueArr;
      this.redHeaderPropArr = redHeaderPropArr;
      // ②除平和质外
      //  a.各体质类型得分相加之和≥11 分时，体质辨识选中“是”
      //  b.各体质类型得分相加之和为 9～10 分,体质辨识选中“倾向是”
      //  c.各体质类型得分相加之和≤8 分,体质辨识选中“否”
      // ③平和质对应选项其中，（2）（4）（5）（13）需反向计分，即选 1→5 分，选 2→4 分，
      // 选 3→3 分，选 4→2 分，选 5→1 分
      //  a.各问题得分相加之和≥17 分，同时其他 8 种体质得分均≤ 8 分，体质辨识选中“是”
      //  b.各问题得分相加之和≥17 分，同时其他 8 种体质得分≤10 分，体质辨识选中“基本是”
      //  d.不满足上述条件时，体质辨识选中“否”
      dataCols.forEach((item, curIndex) => {
        const { prop } = item;
        const otherScores = dataCols
          .filter((_v, index) => index !== curIndex)
          .map((v) => totalScoreMap[v.prop]);
        let choiceVal = "3";
        const curTotalScore = totalScoreMap[prop];
        const basicTotalScoreGt17 = curTotalScore >= 17;
        if (item.label === "平和质") {
          const isPhz = basicTotalScoreGt17 && otherScores.every((v) => v <= 8);
          const basiclyIsPhz =
            basicTotalScoreGt17 && otherScores.every((v) => v <= 10);
          choiceVal = isPhz ? "1" : basiclyIsPhz ? "2" : "3";
        } else {
          const conditionIs = curTotalScore >= 11;
          const conditionIsBasicly = curTotalScore >= 9;
          choiceVal = conditionIs ? "1" : conditionIsBasicly ? "2" : "3";
        }
        bodyTypeDataObj[`${prop}Choice`] = choiceVal;
      });
      let maxScore = 0;
      const allGuidance = healthGuidance.map((_v, index) => index + 1);
      const includePhz = bodyTypeDataObj.peacefulQualityChoice === "1";
      if (includePhz) {
        maxScore = Math.max(...valueArr);
      } else {
        maxScore = Math.max(...valueArr.slice(0, valueArr.length - 2));
      }
      dataCols.forEach((item, curIndex) => {
        const { prop } = item;
        const choiceVal = bodyTypeDataObj[`${prop}Choice`];
        const curTotalScore = totalScoreMap[prop];
        if (curTotalScore === maxScore && choiceVal === "1") {
          bodyTypeDataObj[`${prop}Guidance`] = allGuidance;
        } else {
          bodyTypeDataObj[`${prop}Guidance`] = [];
        }
      });
    },
    headerCellClassFunc({ column }) {
      const { property } = column;
      const { redHeaderPropArr, valueArr } = this;
      return redHeaderPropArr.includes(property) && valueArr.some(Boolean)
        ? "red-header-cell"
        : "";
    },
    //身份证模糊查询
    queryCarNumberAsync: debounce(function (queryString, cb) {
      let results = [];
      queryString = queryString.trim();

      if (queryString === "") {
        cb(results);
        return;
      }

      const find = {
        cardNumber: queryString,
      };
      http
        .post("/health/getResidentList", find)
        .then((res) => {
          if (res.data) {
            res.data.forEach((v) => {
              results.push({
                value: v.cardNumber + " " + v.name,
                cardNumber: v.cardNumber,
                name: v.name,
              });
            });
            lastIdResults = results;
            cb(results);
          } else {
            cb([]);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          cb([]);
        });
    }, 500), // 300ms 的防抖延时

    handleSelect(item) {
      this.personInfo.cardNumber = item.cardNumber;
      http
        .post("/health/getHealthInformation", { cardNumber: item.cardNumber })
        .then((res) => {
          const forms = ["personInfo"];
          //@ts-ignore
          if (res.code === 200) {
            const list = res.data.resident;
            const dataList = res.data;
            forms.forEach((form) => {
              Object.keys(this[form]).forEach((key) => {
                if (list.hasOwnProperty(key)) {
                  this[form][key] = list[key];
                }
              });
            });
            const { height, weight, waist } = dataList;
            if (height && weight) {
              //@ts-ignore
              const bmi = (weight / (height * height)) * 10000;
              if (bmi) {
                this.bmi = bmi;
                console.log(bmi);

                const rowObj = this.questionTableData.find(
                  (v) => v.questionId === "feelingBodyHeavy"
                );

                
                rowObj.score =
                  bmi < 24 ? 1 : bmi < 25 ? 2 : bmi < 26 ? 3 : bmi < 28 ? 4 : 5;
              }
            }
            if (waist) {
              const waitObj = this.questionTableData.find(
                (v) => v.questionId === "abdominalHypertrophy"
              );
              waitObj.score =
                waist < 80
                  ? 1
                  : waist < 85
                    ? 2
                    : waist < 90
                      ? 3
                      : waist < 105
                        ? 4
                        : 5;
            }
            // this.$refs.cardNumberInput.clearSuggestions()
          }
        });
    },

    //姓名模糊查询
    queryNameAsync: debounce(function (queryString, cb) {
      let results = [];
      queryString = queryString.trim();

      if (queryString === "") {
        cb(results);
        return;
      }

      const find = {
        name: queryString,
      };
      http
        .post("/health/getResidentList", find)
        .then((res) => {
          if (res.data) {
            res.data.forEach((v) => {
              results.push({
                value: v.cardNumber + " " + v.name,
                cardNumber: v.cardNumber,
                name: v.name,
              });
            });
            cb(results);
          } else {
            cb([]);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          cb([]);
        });
    }, 500),

    //重置页面
    resetPage() {
      this.questionTableData = getQuestionTableData(); // 假设getQuestionTableData返回初始数据
      this.bodyTypeDataObj = getBodyTypeTableData().bodyTypeDataObj; // 假设getBodyTypeTableData返回初始数据
      this.$refs.personInfoRef.resetFields();
      this.radioChange();
      document.querySelector(".routerView").scrollTop = 0;
    },
    saveData() {
      const {
        bodyTypeDataObj,
        questionTableData,
        personInfo,
        bodyTypeDataKeys,
      } = this;
      const submitObj = { ...personInfo };
      questionTableData.forEach((item) => {
        submitObj[item.questionId] = item.score;
      });

      bodyTypeDataKeys.forEach((key) => {
        submitObj[key] = bodyTypeDataObj[key];
        // 提交数据时，需要将checkbox数组转为字符串
        if (key.includes("Guidance")) {
          submitObj[key] = submitObj[key].join(",");
        }
      });
      this.$refs.personInfoRef.validate((valid) => {
        if (valid) {
          // 筛选出没有分数的项
          const noScoreItems = this.questionTableData
            .map((v, index) => ({ ...v, originalIndex: index })) // 为每个项附加原始索引
            .filter((v) => !v.score); // 筛选出没有分数的项

          // 如果有未打分的项，弹窗提示
          if (noScoreItems.length > 0) {
            const itemNames = noScoreItems
              .map((item, index) => `${item.originalIndex + 1}`)
              .join("、");
            this.$confirm(`问题[${itemNames}]未回答，请先回答`, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {})
              .catch(() => {});
          } else {
            http.post("/healthManage/add", submitObj).then((res) => {
              if (res.code == 200) {
                ElMessage.success(res.message);
                this.resetPage();
              }
            });
          }
        } else {
          document.querySelector(".routerView").scrollTop = 0;
          // document.getElementById("form-header").scrollIntoView({
          //   behavior: "smooth", // 平滑滚动
          //   block: "start", // 滚动到元素顶部
          // });
          return false;
        }
      });
    },
  },
  created() {},
  watch: {
    personInfo: {
      handler(val) {
        const { birthday } = val;
        const i = birthday?.split("-")[0];
        let age = new Date().getFullYear() + "" - i;
        console.log("age", age);

        if (age == 0 || (age && age < 65)) {
          this.personInfo.cardNumber = "";
          this.$confirm(`该居民年龄为${age}岁，不需做中医药健康管理`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$refs.personInfoRef.resetFields();
            })
            .catch(() => {
              this.$refs.personInfoRef.resetFields();
            });
        }
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
:deep(.red-header-cell) {
  color: red !important;
}
.add-health-manage{
  /* height: 100%;
  overflow-y: auto; */

}
.p-10 {
  padding: 10px;
  padding-top: 20px
}
.mt-30 {
  margin-bottom: 30px;
}
.d-flex {
  display: flex;
}
.jc-between {
  justify-content: space-between;
}
.jc-center {
  justify-content: center;
}
.ai-center {
  align-items: center;
}
.px-10 {
  padding-left: 10px;
  padding-right: 10px;
}
.py-10 {
  padding: 10px 0;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-50 {
  margin-bottom: 50px;
}
.text-center {
  text-align: center;
}
.text-left {
  text-align: left;
}
</style>
